package com.example.tobebigfe.web

import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
import com.example.tobebigfe.BuildConfig
import okhttp3.*
import java.io.File


object WebManager {

    private lateinit var preferences: SharedPreferences
    private val httpClient: OkHttpClient = OkHttpClient()
    private lateinit var versionManager: VersionManager
    private lateinit var zipManager: ZipManager

    // 初始化
    fun init(context: Context) {
        preferences = PreferenceManager.getDefaultSharedPreferences(context)
        versionManager = VersionManager(context, httpClient, preferences)
        zipManager = ZipManager(context, httpClient)

    }

    fun updateProject(id: String) {
        versionManager.updateManifest {
            updateOfflineZip(id) {}
        }
    }

    // 根据id和page获取正式的url
    fun getWebUrl(id: String, page: String): String {
        if (isDebugProject(id)) {
            return "http://${preferences.webDevServer()}/$id/dev/$page?t=" + System.currentTimeMillis()
        }
        var version = versionManager.getVersion(id)
        if (version.isNullOrBlank() || !zipManager.hasOfflineFiles(id, version)) {
            version = versionManager.getBuiltinVersion(id)!!
            if (!zipManager.hasOfflineFiles(id, version)) {
                zipManager.unzipBuiltin(id, version)
            }
        }
        return "${WebConst.WEB_BASE_URL}$id/$version/$page"
    }

    fun getOfflineFile(id: String, version: String, filePath: String): File {
        return zipManager.getOfflineFile(id, version, filePath)
    }

    private fun updateOfflineZip(id: String, callback: OfflineZipUpdatedCallback) {
        if (isDebugProject(id)) {
            callback(null)
            return
        }
        if (id.isBlank()) {
            callback(IllegalArgumentException("project id is blank"))
            return
        }
        val version = versionManager.getVersion(id)
        if (version.isNullOrBlank()) {
            callback(IllegalArgumentException("project id is invalid"))
            return
        }
        zipManager.updateOfflineZip(id, version, callback)
    }

    private fun isDebugProject(id: String): Boolean {
        return BuildConfig.DEBUG && preferences.isWebDevEnabled() && id == preferences.webDevProject()
    }

}

private fun SharedPreferences.isWebDevEnabled(): Boolean {
    return getBoolean("webDev.enabled", false)
}

private fun SharedPreferences.webDevProject(): String? {
    return getString("webDev.project", null)
}

private fun SharedPreferences.webDevServer(): String? {
    return getString("webDev.server", null)
}